#!/usr/bin/python3
# -*- coding: UTF-8 -*-
# bing 单词批量翻译
# 编写一个项目，将自己所监听的网页收集起来
import requests
import os
import time
from lxml import etree

def readFile():
    with open('word.txt', 'r', encoding='utf-8', errors='ignore') as fo:
        cont = fo.readlines()
        return cont


def writeFile(fn, cntl):
    content = '\n'.join(cntl)
    with open(fn, 'w', encoding='utf-8') as fd:
        fd.write(content)


def bingTranslateEn2Zh(q):
    urla = 'https://cn.bing.com/dict/search'
    pld = {"q": q}
    rsp = requests.get(urla, params=pld)
    html = etree.HTML(rsp.text)
    # '//div[@id="content"]/ul/li/text()'
    xp0 = "//div[@id='headword']/h1/strong/text()"
    xp1 = "//div[@class='qdef']/ul/li"
    rwd = html.xpath(xp0)
    qn = rwd[0] if len(rwd) == 1 else q
    result = html.xpath(xp1)
    if len(result) > 0:
        for t in result:
            a = t.xpath("./span[1]")[0].text
            b = t.xpath("./span[2]/span")[0].text
            a = "net." if a == "网络" else a
            qn = qn + '  |  ' + a + " " + b
            # print(t.tag, a, b, end='\n ')
    else:
        # 单词拼写错误，提示正确可能为
        xp2 = "//div[@class='web_div1']/div"
        result = html.xpath(xp2)
        for div in result:
            w = div.xpath("./a/text()")[0]
            m = div.xpath("./div/text()")[0]
            qn = qn + "  |  " + w + ': '+m
            # print(w, m)
    return qn

# 对内容有大小的限制，不太好使用
# 有时间使用python的邮件推送模块实现


if __name__ == "__main__":
    lines = readFile()
    c = 0
    t = len(lines)
    cntl = []
    i=0
    t = len(lines)
    for q in lines:
        q = q.replace('\n', '')
        # 查询单词为空，不在进行后续
        if len(q) == 0:
            continue
        else:
            time.sleep(1)
        qn = bingTranslateEn2Zh(q)
        c += 1
        print('==> %d/%d' % (c, t))
        cntl.append(qn)
        i +=1
        print("==> %d/%d"%(i,t))
    writeFile('word1.txt', cntl)
    print("==> done!")
